package com.masterclient.app.modules.chezhubang;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.eoner.managerlibrary.Tools;
import com.masterclient.app.BaseActivity;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.eoner.baselib.utils.sp.SPUtils;
import com.masterclient.app.widget.TitlebarView;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wendu.dsbridge.OnReturnValue;

/**
 * @auther hjian
 * @date 2019/11/12.
 */
public class CzbWebActivity extends BaseActivity {

    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.dwebview)
    X5WebView webView;
    @BindView(R.id.czb_titlebar)
    TitlebarView czbTitlebar;

    private boolean isFirstLoad = true;
    public SelectMapDialog dialog;

    private LocationWebChromeClient mLocationWebChromeClient;
    public boolean isBdMap = false,isGdMap = false,isTxMap = false;
    public String title;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_czb_web);
        ButterKnife.bind(this);

        title = "优惠加油";
        dialog = new SelectMapDialog(this);

        if (isFirstLoad){
            setDialogData();
            isFirstLoad = false;
        }



        czbTitlebar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                if (webView == null) return;
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
            }

            @Override
            public void rightClick() {
                finish();

            }
        });

        setWebViewListener();
    }


    private void setWebViewListener() {
        //加载的url按规定的使用即可
        String url = getBundleString("url");
        setAppInfoCookies();
        webView.loadUrl(url);
        final CzbJsObject czbJsObject = new CzbJsObject(this);
        webView.addJavascriptObject(new CzbJsApi(this), null);
        webView.addJavascriptInterface(czbJsObject, "czb");
        mLocationWebChromeClient = new LocationWebChromeClient(this);

        webView.setWebChromeClient(mLocationWebChromeClient);

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                if (url.startsWith("weixin://") || url.contains("alipays://platformapi")) {//如果微信或者支付宝，跳转到相应的app界面,
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(CzbWebActivity.this, "未安装相应的客户端", Toast.LENGTH_LONG).show();
                    }
                    return true;
                }

                if (url.startsWith("http://m.amap.com")) {// http://m.amap.com
                    webView.loadUrl(url);
                    return true;
                }

                if (url.startsWith("https://uri.amap.com")) {//安装高德则打开导航

//                    webView.goBack();
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(CzbWebActivity.this, "未安装高德的客户端", Toast.LENGTH_LONG).show();
                    }
                    return true;
                }

                if (url.startsWith("http://ditu.amap.com")||url.startsWith("https://ditu.amap.com")){
                    return true;
                }

                /**
                 *
                 * 设置 Header 头方法
                 * window.czb.extraHeaders(String key, String value)
                 */
                if (czbJsObject != null && czbJsObject.getKey() != null) {
                    Map extraHeaders = new HashMap();
                    extraHeaders.put(czbJsObject.getKey(), czbJsObject.getValue());
                    webView.loadUrl(url, extraHeaders);
                } else {
                    webView.loadUrl(url);
                }
                return true;
            }
        });
    }

    private void setDialogData(){
        isBdMap = Tools.isAppAvilible(this,"com.baidu.BaiduMap");
        isGdMap = Tools.isAppAvilible(this,"com.autonavi.minimap");
        isTxMap = Tools.isAppAvilible(this,"com.tencent.map");
    }

    public void setDialog(Map<String , String> map){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isBdMap||isGdMap||isTxMap){
                    dialog.show();
                    dialog.setVisiable(isGdMap,isBdMap,isTxMap);
                    dialog.setData(map.get("startLongitude"),map.get("startLatitude"),
                            map.get("endLongitude"),map.get("endLatitude"),map.get("name"));
                }else {
                    showToast("请下载高德百度腾讯地图软件进行导航");
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirstLoad)
            setDialogData();
    }

    //返回键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }

    public void setCzbTitlebar(String title){
        this.title = title;
        czbTitlebar.setTitle(title);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mLocationWebChromeClient != null && mLocationWebChromeClient.getLocationWebChromeClientListener() != null) {
            mLocationWebChromeClient.getLocationWebChromeClientListener().onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0&&resultCode == RESULT_OK){
            String token = SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN);
            if (!TextUtils.isEmpty(token)) {
                webView.callHandler("loginSuccess", new Object[]{token}, new OnReturnValue<String>() {
                    @Override
                    public void onValue(String retValue) {
                    }
                });
            }
        }
        if (mLocationWebChromeClient != null && mLocationWebChromeClient.getLocationWebChromeClientListener() != null) {
            if (mLocationWebChromeClient.getLocationWebChromeClientListener().onReturnFromLocationSetting(requestCode)) {
                return;
            }
        }
    }
}
